class VoiceUtils {
  constructor() {
    this.mediaRecorder = null;
    this.audioChunks = [];
    this.isRecording = false;
    this.speechSynthesis = window.speechSynthesis;
    this.speechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    this.recognition = null;
    this.finalTranscript = '';
  }

  // 初始化语音识别
  initRecognition(onResult, onEnd) {
    if (!this.speechRecognition) {
      console.error('浏览器不支持语音识别');
      return false;
    }

    try {
      this.recognition = new this.speechRecognition();
      this.recognition.continuous = true;
      this.recognition.interimResults = true;
      this.recognition.lang = 'zh-CN';
      this.finalTranscript = '';

      this.recognition.onstart = () => {
        console.log('语音识别开始');
      };

      this.recognition.onresult = (event) => {
        let interimTranscript = '';
        let finalTranscript = '';

        for (let i = event.resultIndex; i < event.results.length; i++) {
          const transcript = event.results[i][0].transcript;
          if (event.results[i].isFinal) {
            finalTranscript += transcript;
          } else {
            interimTranscript += transcript;
          }
        }

        console.log('临时识别结果:', interimTranscript);
        console.log('最终识别结果:', finalTranscript);

        if (finalTranscript) {
          this.finalTranscript = finalTranscript;
          onResult(finalTranscript);
        } else {
          onResult(interimTranscript);
        }
      };

      this.recognition.onerror = (event) => {
        console.error('语音识别错误:', event.error);
      };

      this.recognition.onend = () => {
        console.log('语音识别结束，最终文本:', this.finalTranscript);
        onEnd();
      };

      return true;
    } catch (error) {
      console.error('初始化语音识别失败:', error);
      return false;
    }
  }

  // 开始录音
  startRecording() {
    if (this.isRecording) {
      console.log('已经在录音中');
      return;
    }

    navigator.mediaDevices.getUserMedia({ audio: true })
      .then(stream => {
        console.log('获取音频流成功');
        this.mediaRecorder = new MediaRecorder(stream);
        this.audioChunks = [];
        this.isRecording = true;
        this.finalTranscript = '';

        this.mediaRecorder.ondataavailable = (event) => {
          console.log('收到音频数据');
          this.audioChunks.push(event.data);
        };

        this.mediaRecorder.onstop = () => {
          console.log('录音停止');
        };

        this.mediaRecorder.start();
        console.log('开始录音');
      })
      .catch(error => {
        console.error('获取音频流失败:', error);
      });
  }

  // 停止录音
  stopRecording() {
    if (!this.isRecording) {
      console.log('当前没有在录音');
      return Promise.resolve(null);
    }

    return new Promise((resolve) => {
      this.mediaRecorder.onstop = () => {
        const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });
        this.isRecording = false;
        console.log('录音已停止，生成音频文件');
        resolve(audioBlob);
      };

      this.mediaRecorder.stop();
      this.mediaRecorder.stream.getTracks().forEach(track => track.stop());
    });
  }

  // 播放语音
  playVoice(text, onEnd) {
    try {
      const utterance = new SpeechSynthesisUtterance(text);
      utterance.lang = 'zh-CN';
      utterance.rate = 1.0;
      utterance.onend = () => {
        console.log('语音播放结束');
        onEnd?.();
      };
      this.speechSynthesis.speak(utterance);
      console.log('开始播放语音');
    } catch (error) {
      console.error('语音播放失败:', error);
    }
  }

  // 停止播放
  stopVoice() {
    this.speechSynthesis.cancel();
    console.log('停止所有语音播放');
  }
}

export const voiceUtils = new VoiceUtils(); 